package com.youi.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

import javax.servlet.ServletRequest;

/**
 * 请求响应工具
 * @author erdong.Chan
 *
 */
public class HttpUtil {

	public final static String POST="POST";
	
	public final static String ContentType1="application/x-www-form-urlencoded";
	
	public final static String ContentType2="application/json;charset=utf-8";

	/**
	 * 公共请求响应工具
	 * @param urlStr
	 * @param method
	 * @param memo 备注
	 * @return
	 */
	public static String Action(String urlStr,String params,String memo){
		return Action(urlStr, POST, params, ContentType1, memo);
	}
	
	/**
	 * 公共请求响应工具
	 * @param urlStr
	 * @param method
	 * @param memo 备注
	 * @return
	 */
	public static String Action(String urlStr,String params,String contentType, String memo){
		return Action(urlStr, POST, params, contentType, memo);
	}
	
	/**
	 * 请求响应工具
	 * @param urlStr
	 * @param method
	 * @return
	 */
	private static String Action(String urlStr,String method,String params,String contentType,String memo){
		LogUtil.Info("响应url"+urlStr);
		LogUtil.Info("开始"+memo);
		LogUtil.Info("params="+params);
		try {
			URL url = new URL(urlStr);
			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setRequestMethod(method);
			urlConnection.setUseCaches(false); 
			urlConnection.setInstanceFollowRedirects(true);
			urlConnection.setRequestProperty("Content-Type",contentType);
			urlConnection.setRequestProperty("Charset", "UTF-8"); 
			urlConnection.connect();
			DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
			if (params!=null&&params.length()>0) {
				out.write(params.getBytes("UTF-8"));
			}
	        out.flush();
	        out.close(); 
	        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
	        String line;
	        String responseStr="";
	        while ((line = reader.readLine()) != null){
	        	responseStr+=line;
	        }
	        reader.close();
	        urlConnection.disconnect();
	        System.err.println("postresult="+responseStr);
	        LogUtil.Info("postresult="+responseStr);
	        return responseStr;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LogUtil.Info(memo+"异常");
			LogUtil.Info(e.toString());
			return null;
		}
	}
	
	/**
	 * 公共请求响应工具
	 * @param urlStr
	 * @param method
	 * @return
	 */
	public static String JPushAction(String urlStr,String method,String params,String memo,String base64Auth,String contentType){
		LogUtil.Info("响应url"+urlStr);
		LogUtil.Info("开始"+memo);
		LogUtil.Info("params="+params);
		try {
			URL url = new URL(urlStr);
			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setRequestMethod(method);
			urlConnection.setUseCaches(false); 
			urlConnection.setInstanceFollowRedirects(true);
			urlConnection.setRequestProperty("Content-Type",contentType);
			urlConnection.setRequestProperty("Charset", "UTF-8"); 			
			urlConnection.setRequestProperty("Authorization","Basic "+base64Auth);
			urlConnection.connect();
			DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
			if (params!=null&&params.length()>0) {
				out.write(params.getBytes("UTF-8"));
			}
	        out.flush();
	        out.close(); 
	        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
	        String line;
	        String responseStr="";
	        while ((line = reader.readLine()) != null){
	        	responseStr+=line;
	        }
	        reader.close();
	        urlConnection.disconnect();
	        LogUtil.Info("postresult="+responseStr);
	        return responseStr;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LogUtil.Info(memo+"异常");
			LogUtil.Info(e.toString());
			return null;
		}
	}
	
	public static String Action(String urlStr,String method,Map<String, String> params,String memo){
		LogUtil.Info("响应url"+urlStr);
		LogUtil.Info("开始"+memo);
		LogUtil.Info("params="+params);
		try {
			URL url = new URL(urlStr);
			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setRequestMethod(method);
			urlConnection.setUseCaches(false); 
			urlConnection.setInstanceFollowRedirects(true);
			urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			urlConnection.setRequestProperty("Charset", "UTF-8"); 
			urlConnection.connect();
			DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
			if (params!=null&&params.size()>0) {
				out.write(getUrlParamsFromMap(params).getBytes());
			}
	        out.flush();
	        out.close(); 
	        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
	        String line;
	        String responseStr="";
	        while ((line = reader.readLine()) != null){
	        	responseStr+=line;
	        }
	        reader.close();
	        urlConnection.disconnect();
	        LogUtil.Info("postresult="+responseStr);
	        return responseStr;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LogUtil.Info(memo+"异常");
			LogUtil.Info(e.toString());
			return null;
		}
	}
	
	 /**
     * description:将map转换成url参数格式: name1=value1&name2=value2
     *
     * @param map
     * @return
     */
    public static String getUrlParamsFromMap(Map<String, String> map) {
        try {
            if (null != map) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                            .append("&");
                }
                String content = stringBuilder.toString();
                if (content.endsWith("&")) {
                    content = content.substring(0, content.length() - 1);
                }
                return content;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("map数据异常！" + e);
        }
        return "";
    }
    
    /**
     * 解析 出content-Type 为  application/x-www-form-urlencoded ，application/json , text/xml 这三种提交方式的 数据 
     **/
    public static String getBodyString(ServletRequest request) {
    	StringBuilder sb = new StringBuilder();
    	InputStream inputStream = null;
    	BufferedReader reader = null;
    	try {
    		inputStream = request.getInputStream();
    		reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
    		String line = "";
    		while ((line = reader.readLine()) != null) {
    			sb.append(line);
    		}
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
    }
    
    public static String getUrlParamsForMap(Map<String, Object> map) {      
    	try {
            if (null != map) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                            .append("=")
                            .append(URLEncoder.encode("UTF-8"))
                            .append("&");
                }
                String content = stringBuilder.toString();
                if (content.endsWith("&")) {
                    content = content.substring(0, content.length() - 1);
                }
                return content;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("map数据异常！" + e);
        }
        return "";
    }
}
